/**
 * 
 */
package com.autonavi.car.si.FileStore.impl;

import java.io.File;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.autonavi.car.si.FileStore.FileStore;
import com.autonavi.car.si.FileStore.model.FileVO;
import com.autonavi.car.si.FileStore.model.FileVO.FileOperate;
import com.autonavi.car.si.FileStore.task.FileQueue;
import com.autonavi.car.si.FileStore.util.StringUtil;

/**
 * @author kucheng.liao@autonavi.com
 * @date Nov 24, 2014
 * 
 */
public class FileStoreImpl implements FileStore {

	private static Logger log = LoggerFactory.getLogger(FileStoreImpl.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.autonavi.car.si.FileStore.FileStore#store(java.io.InputStream,
	 * java.lang.String)
	 */
	public String store(InputStream in) {
		if (null != in) {
			FileVO vo = new FileVO();
			vo.setIn(in);
			vo.setOperate(FileOperate.STOR);
			FileQueue.push(vo);
			vo.dataWait();
			if (vo.getStatus() == 200) {
				return vo.getStorePath() + File.separator + vo.getUniqueFileName();
			}
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.autonavi.car.si.FileStore.FileStore#download(java.lang.String)
	 */
	public InputStream download(String filePath) {
		if (StringUtil.isNotEmpty(filePath)) {
			String[] sts = findFile(filePath);
			if (null != sts) {
				FileVO vo = new FileVO();
				vo.setOperate(FileOperate.GET);
				vo.setSlice(Integer.parseInt(sts[1]));
				vo.setUniqueFileName(sts[2]);
				vo.setStorePath(sts[0]+File.separator+sts[1]);
				FileQueue.push(vo);
				vo.dataWait();
				return vo.getIn();
			} else {
				if (log.isWarnEnabled()) {
					log.warn("<!-----------无效的请求路径" + filePath);
				}
			}
		}
		return null;
	}

	private String[] findFile(String filePath) {
		char[] chars = filePath.toCharArray();
		String[] sts = new String[3];
		int tmp = chars.length;
		int i = tmp - 1;
		for (; i > -1; i--) {
			if (chars[i] == '/' || chars[i] == '\\') {
				if (null == sts[2]) {
					sts[2] = filePath.substring(i + 1, tmp);
					tmp=i;
				}else{
					sts[0]=filePath.substring(0, i);
					sts[1]=filePath.substring(i+1, tmp);
					return sts;
				}
			}
		}
		return null;
	}

//	public static void main(String[] args) {
//		FileStoreImpl store = new FileStoreImpl();
//		String[] sts = store.findFile("2_1/2_2\\2_3");
//		if (null != sts) {
//			for (String st : sts) {
//				System.out.println(st);
//			}
//		}
//	}
}
